import {Observable, Observer, Subscription} from 'rxjs';
import {filter, share} from 'rxjs/operators';

export class ReactiveEvent {
  observable: Observable<any>;
  observer: Observer<any>;

  constructor() {
    this.observable = new Observable((observer: Observer<any>) => {
      this.observer = observer;
    }).pipe(share());
  }

  /**
   * 广播事件
   */
  broadcast(event) {
    if (this.observer != null) {
      this.observer.next(event);
    }
  }

  /**
   * 使用回调订阅事件
   */
  subscribe(eventName, callback) {
    const subscriber: Subscription = this.observable
      .pipe(
        filter(event => {
          return event.name === eventName;
        })
      )
      .subscribe(callback);
    return subscriber;
  }
  on(eventName): Observable<any> {
    return this.observable
      .pipe(
        filter(event => {
          return event.name === eventName;
        })
      );
  }

  /**
   * 取消订阅
   */
  destroy(subscriber: Subscription) {
    subscriber.unsubscribe();
  }
}
